package com.education.basic.dao.impl;

import javax.annotation.Resource;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.education.basic.dao.TeacherDao;
import com.education.basic.entity.Teacher;
import com.yunshangwoniu.core.baseDao.impl.BaseDaoImpl;
import com.yunshangwoniu.core.utils.Logger;

import java.util.List;

@Component("teacherDao")
public class TeacherDaoImpl extends BaseDaoImpl<Teacher> implements TeacherDao
{
	@Resource
	private SessionFactory sessionFactory;

    @Override
    @Transactional
    public List<Teacher> queryAll() {
        String hql  = "from Teacher t";
        Session session = sessionFactory.getCurrentSession();
        Query q = session.createQuery(hql);
        @SuppressWarnings("unchecked")
		List<Teacher> list = q.list();
        Logger.debug(this.getClass(),String.format("get all teacher size is [%s]",list.size()));
        return list;
    }

    @Override
    public Teacher getByUsername(String username) {
        Session session = sessionFactory.getCurrentSession();
        String hql = "from Teacher t where t.username=?";
        Query q = session.createQuery(hql);
        q.setString(0,username);
        Teacher t = null;
        try {
            t = (Teacher) q.uniqueResult();
            Logger.debug(this.getClass(),String.format("get teacher success by username:%s",username));
        } catch (HibernateException e) {
            Logger.debug(this.getClass(), String.format("get teacher failed by username:%s exsit more 2 !!!", username));
        }
        return t;
    }

    @Override
	@Transactional
	public Teacher getByDepartmentIdAndTitleCode(String departmentId, String titleCode)
	{
		Logger.debug(this.getClass(), String.format("excute getByDepartmentIdAndTitleCode from Teacher when [departmentCode:%s;titleCode:%s]", departmentId,titleCode));
		Session session = sessionFactory.getCurrentSession();
		String hql = "from Teacher t where t.departmentId=? and t.titleCode=? order by t.createTime desc limit 0,1";
		Query q  = session.createQuery(hql).setFirstResult(0).setMaxResults(1);
		q.setString(0, departmentId);
		q.setString(1, titleCode);
		Teacher t2 = (Teacher)q.uniqueResult();
		if(t2==null)
		{
			Logger.debug(this.getClass(), String.format(" excute getByDepartmentIdAndTitleCode not found!! Teacher like [departmentId:%s;titleCode:%s]", departmentId,titleCode));
			return null;
		}else
		{
			Logger.debug(this.getClass(),String.format("excute getByDepartmentIdAndTitleCode sucucss!! [name:%s;username:%s]", t2.getName(),t2.getUsername()));
			return t2;
		}
	}

}
